package com.yunwaikeji.gy_tool_library.utils.permission;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import java.util.ArrayList;
import java.util.List;

public class GYPermissionActivity extends AppCompatActivity {
    private PermissionResult permissionResult;

    public GYPermissionActivity setPermissionResult(PermissionResult permissionResult) {
        this.permissionResult = permissionResult;
        return this;
    }

    private List<String> permissionList;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        permissionList = getIntent().getStringArrayListExtra("permissionList");
        if (permissionList != null && permissionList.size() > 0) {
            String[] permissions = permissionList.toArray(new String[permissionList.size()]);
            ActivityCompat.requestPermissions(this, permissions, 0);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (permissionResult != null) {
            List<GYPermissionModel> permissionModelList = new ArrayList<>();
            for (int i = 0; i < permissions.length; i++) {
                GYPermissionModel permissionModel = new GYPermissionModel();
                permissionModel.setName(permissions[i]);
                permissionModel.setAuthorized(grantResults[i] == 0);
                permissionModelList.add(permissionModel);
            }
            permissionResult.permissionResult(permissionModelList);
        }
    }
}
